﻿using System;
using UnityEngine;

namespace DL.AudioSystem
{
    /// <summary>
    /// 音频构建器
    /// </summary>
    public class AudioBuilder
    {
        private readonly AudioManager m_AudioManager;
        private SoundData m_Data;
        private Vector3 m_Position = Vector3.zero;
        private Quaternion m_Rotation = Quaternion.identity;
        private bool m_RedomPitch; //随机音高
        private SoundType m_SoundType = SoundType.Null;

        public AudioBuilder(AudioManager audioManager)
        {
            m_AudioManager = audioManager;
        }

        public void Reset()
        {
            m_Data = null;
            m_Position = Vector3.zero;
            m_Rotation = Quaternion.identity;
            m_RedomPitch = false; //随机音高
            m_SoundType = SoundType.Null;
        }

        /// <summary>
        /// 通过类型获取
        /// </summary>
        /// <param name="type"></param>
        /// <param name="clipName"></param>
        /// <returns></returns>
        public AudioBuilder WithSoundType(SoundType type,string clipName = default)
        {
            WithSoundData(m_AudioManager.GetSoundDataByType(type,clipName));
            return this;
        }
        
        /// <summary>
        /// 直接使用资源
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public AudioBuilder WithSoundData(SoundData data)
        {
            m_Data = data;
            return this;
        }
        
        public AudioBuilder WithPosition(Vector3 pos)
        {
            m_Position = pos;
            return this;
        }
        
        public AudioBuilder WithRotation(Quaternion rot)
        {
            m_Rotation = rot;
            return this;
        }
        
        public AudioBuilder WithRedomPitch()
        {
            m_RedomPitch = true;
            return this;
        }

        public void Play()
        {
            if (!m_AudioManager.CanPlayeAudio(m_SoundType, data: m_Data)) return;

            var audioEmitter = m_AudioManager.Get();
            audioEmitter.Init(m_Data);
            audioEmitter.transform.SetPositionAndRotation(m_Position, m_Rotation);
            audioEmitter.transform.SetParent(m_AudioManager.transform);

            if (m_RedomPitch)
            {
                audioEmitter.WithRedomPitch();
            }

            if (m_Data.frequentAudio)
            {
                m_AudioManager.EqueueFrequentAudioEmitter(m_SoundType, audioEmitter);
            }
            audioEmitter.Play();
        }

    }
}